package com.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.app.common.Result;
import com.app.mapper.AreaMapper;
import com.app.mapper.CityMapper;
import com.app.mapper.CustomerServiceMapper;
import com.app.mapper.UserMapper;
import com.app.model.*;
import com.app.service.BusinessService;
import com.app.service.CustomerServiceService;
import com.app.service.UserService;
import com.app.vo.IntegralVoucherPageVo;
import com.app.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJQueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class CustomerServiceServiceImpl extends ServiceImpl<CustomerServiceMapper, CustomerServiceModel> implements CustomerServiceService {
    @Autowired
    private CustomerServiceMapper customerServiceMapper;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserServiceImpl userServiceImpl;


    /**
     * 新增客服/修改客服
     *
     * @param dto
     * @return
     */
    @Override
    public Result addAndUpdate(CustomerServiceModel dto) {
        //参数校验
        if (ObjectUtil.isNull(dto)) {
            return Result.error(400, "客服对象信息为空，不予新增、修改");
        }
        if (dto.getAreaId() == null) {
            return Result.error(400, "未指定客服负责的区域，不予新增、修改");
        }
        CustomerServiceModel customerServiceModel = new CustomerServiceModel();
        if (!Objects.equals(dto.getAreaId(), customerServiceModel.getAreaId()) || !Objects.equals(dto.getCityId(), customerServiceModel.getCityId())) {
            Wrapper<CityModel> wrapper = new QueryWrapper<CityModel>()
                    .eq("city_id", dto.getCityId());
            CityModel cityModel = cityMapper.selectOne(wrapper);
            ArrayList<Integer> list = new ArrayList<>();
            list.add(cityModel.getProvinceId());
            list.add(dto.getCityId());
            list.add(dto.getAreaId());
            customerServiceModel.setAreaCode(JSON.toJSONString(list));
        }
        if (dto.getValue() != null) {
            dto.setAreaCode(JSON.toJSONString(dto.getValue()));
        }
        if (dto.getId() != null) {//修改
            if (StrUtil.isNotBlank(dto.getPhone())) {
                Wrapper<CustomerServiceModel> wrapper = new QueryWrapper<CustomerServiceModel>()
                        .eq("id", dto.getId());
                customerServiceModel = customerServiceMapper.selectOne(wrapper);
                if (ObjectUtil.isNull(customerServiceModel)) {
                    return Result.error(400, "该客服不存在，请先添加客服信息");
                }
            }
            //构建修改条件
            if (StrUtil.isNotBlank(dto.getNickname())) {
                customerServiceModel.setNickname(dto.getNickname());
            }
            if (StrUtil.isNotBlank(dto.getName())) {
                customerServiceModel.setName(dto.getName());
            }
            if (StrUtil.isNotBlank(dto.getEmail())) {
                customerServiceModel.setEmail(dto.getEmail());
            }
            if (dto.getMaxNum() != null) {
                customerServiceModel.setMaxNum(dto.getMaxNum());
            }
            if (dto.getAreaId() != null) {
                customerServiceModel.setAreaId(dto.getAreaId());
            }
            //更该手机号
            if (StrUtil.isNotBlank(dto.getPhone())) {
                Wrapper<CustomerServiceModel> wrapper = new QueryWrapper<CustomerServiceModel>()
                        .eq("phone", dto.getPhone());
                List<CustomerServiceModel> customerServiceModelp = customerServiceMapper.selectList(wrapper);
                if (customerServiceModelp.isEmpty()) {
                    customerServiceModel.setPhone(dto.getPhone());
                }
            }
            // 创建Timestamp对象
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            dto.setUpdateTime(timestamp);
            customerServiceMapper.updateById(dto);
            return Result.success("修改成功");
        } else {//新增
            if (StrUtil.isNotBlank(dto.getPhone())) {
                Wrapper<CustomerServiceModel> wrapper = new QueryWrapper<CustomerServiceModel>()
                        .eq("phone", dto.getPhone());
                customerServiceModel = customerServiceMapper.selectOne(wrapper);
                if (ObjectUtil.isNotNull(customerServiceModel)) {
                    return Result.error(400, "该客服已经存在，请换手机号添加");
                }
            }
            // 创建Timestamp对象
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            dto.setCreateTime(timestamp);
            dto.setUpdateTime(timestamp);
            if (StrUtil.isBlank(dto.getNickname())) {
                dto.setNickname("商家联盟客服");
            }
            dto.setStatus(2);
            dto.setIsDel(2);
            dto.setNowNum(0);
            dto.setMaxNum(100);
            customerServiceMapper.insert(dto);
            return Result.success("添加成功");
        }
    }

    /**
     * 删除客服信息（假删除）
     *
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {

        if (ObjectUtil.isNull(id)) {
            return Result.error(400, "请指定要删除的客服id");
        }
        CustomerServiceModel customerServiceModel = customerServiceMapper.selectById(id);
        if (ObjectUtil.isNull(customerServiceModel)) {
            return Result.success("要删除的客服信息不存在");
        }
        String businessIds = customerServiceModel.getVipIds();
        List<Integer> integerList = convertStringToIntList(businessIds, ",");
        if (!Objects.requireNonNull(integerList).isEmpty()) {
            return Result.error(422, "该客服还有对接的vip用户，不予删除");
        }
        customerServiceModel.setIsDel(1);
        customerServiceMapper.updateById(customerServiceModel);
        return Result.success("删除成功");
    }


    /**
     * 客服绑定新的商家们
     *
     * @param vipIds
     * @param customerId
     * @param type       1解绑  2绑定
     * @return
     */
    @Override
    public Result updateBusinessIds(List<Integer> vipIds, Integer customerId, Integer type) {
        if (ObjectUtil.isNull(vipIds) || vipIds.isEmpty()) {
            return Result.success("请提供要绑定的商家信息");
        }
        if (ObjectUtil.isNull(customerId)) {
            return Result.error(400, "提供要绑定的客户id");
        }
        CustomerServiceModel customerServiceModel = customerServiceMapper.selectById(customerId);
        if (ObjectUtil.isNull(customerServiceModel) || customerServiceModel.getIsDel() == 1) {
            return Result.error(400, "客服信息不存在");
        }
        if (type != 1 && type != 2) {
            return Result.error(400, "type类型错误");
        }
        String businessIds1 = customerServiceModel.getVipIds();
        List<Integer> integerList = convertStringToIntList(businessIds1, ",");
        if (type == 2) {//绑定
            integerList.addAll(vipIds);
            int size = integerList.size();
            if (customerServiceModel.getMaxNum() < size) {
                return Result.error(400, "客服能绑定的商家数量超过上限");
            }
            String s = convertIntListToString(integerList, ",");
            customerServiceModel.setVipIds(s);
            customerServiceMapper.updateById(customerServiceModel);
            return Result.success("商家绑定成功");
        } else {//解绑
            if (integerList.isEmpty()) {
                return Result.error(400, "客服未绑定任何商家商家");
            }
            for (Integer businessId : vipIds) {
                integerList.remove(businessId);
            }
            String s = convertIntListToString(integerList, ",");
            customerServiceModel.setVipIds(s);
            customerServiceMapper.updateById(customerServiceModel);
            return Result.success("解绑成功");
        }

    }

    /**
     * 查询客服详情
     *
     * @param id
     * @return
     */
    @Override
    public Result detail(Integer id) {
        if (ObjectUtil.isNull(id)) {
            return Result.error(400, "请提供要查询的客服id");
        }
        CustomerServiceModel customerServiceModel = customerServiceMapper.selectById(id);
        if (StrUtil.isNotBlank(customerServiceModel.getAreaCode())) {
            List<String> list = JSON.parseObject(customerServiceModel.getAreaCode(), new TypeReference<List<String>>() {
            });
            customerServiceModel.setValue(list);
        }
        return Result.success(customerServiceModel);
    }

    /**
     * 根据客服id查询客服绑定的vip用户的信息
     *
     * @param id
     * @return
     */
    @Override
    public Result businessList(Integer id,Integer page, Integer limit, String keyword, String areaId) {
        if (ObjectUtil.isNull(id)) {
            return Result.error(400, "请提供要查询的客服id");
        }
        CustomerServiceModel customerServiceModel = customerServiceMapper.selectById(id);
        String vipIds = customerServiceModel.getVipIds();
        List<Integer> list = convertStringToIntList(vipIds, ",");
        if (list.isEmpty()) {
            return Result.success(null);
        }
        MPJQueryWrapper<UserModel> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.selectAll(UserModel.class);
        queryWrapper.select("ta.area", "tc.city", "tp.province");
        queryWrapper.leftJoin("tbc_areas ta on t.area_id = ta.area_id");
        queryWrapper.leftJoin("tbc_cities tc on ta.city_id = tc.city_id");
        queryWrapper.leftJoin("tbc_provinces tp on tc.province_id = tp.province_id");
        queryWrapper.in("t.id", list);
        queryWrapper.eq("t.vip", 1);
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.eq("t.area_id", areaId);
        }
        if (StrUtil.isNotBlank(keyword)) {
            queryWrapper.last("AND (t.name LIKE CONCAT('%', " + keyword + ", '%') OR t.phone LIKE CONCAT('%', " + keyword + ", '%')) order by t.id desc");
        }
        Page<UserModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        Page<UserModel> userModelPage = userMapper.selectPage(pages, queryWrapper);
        List<UserModel> userList = userModelPage.getRecords();
        for (UserModel userModel : userList) {
            if (userModel.getProvince() != null) {
                userModel.setAreaText(userModel.getProvince() + "/" + userModel.getCity() + "/" + userModel.getArea());
            }
            userModel.setOpenId(null);
        }
        UserVo vo = new UserVo();
        vo.setList(userModelPage.getRecords());
        vo.setCount((int) userModelPage.getTotal());
        return Result.success(vo);
    }

    /**
     * 更改客服状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public Result updateStatus(Integer id, Integer status) {
        if (ObjectUtil.isNull(id) || status == null) {
            return Result.error(400, "请指定要删除的客服id或要更改成的状态");
        }
        CustomerServiceModel customerServiceModel = customerServiceMapper.selectById(id);
        if (ObjectUtil.isNull(customerServiceModel)) {
            return Result.success("要更改的客服信息不存在");
        }
        if (status == 2) {
            String businessIds = customerServiceModel.getVipIds();
            List<Integer> integerList = convertStringToIntList(businessIds, ",");
            if (!integerList.isEmpty()) {
                return Result.error(422, "该客服还有对接的商家，请更改其商家信息在禁用该客服");
            }
            customerServiceModel.setStatus(status);
        } else if (status == 1) {
            customerServiceModel.setStatus(status);
        }
        customerServiceMapper.updateById(customerServiceModel);
        return Result.success("更改成功");
    }

    /**
     * 把商家从客服A转移给商家B
     *
     * @param aid
     * @param bid
     * @param businessId
     * @return
     */
    @Override
    public Result moveFromAtoB(Integer aid, Integer bid, Integer businessId) {
        if (ObjectUtil.isNull(aid) || ObjectUtil.isNull(bid) || ObjectUtil.isNull(businessId)) {
            return Result.error(400, "参数错误，不予移动");
        }
        CustomerServiceModel customerServiceModela = customerServiceMapper.selectById(aid);
        if (ObjectUtil.isNull(customerServiceModela)) {
            return Result.error(400, "原的客服信息不正确，不存在该客服");
        }
        CustomerServiceModel customerServiceModelb = customerServiceMapper.selectById(bid);
        if (ObjectUtil.isNull(customerServiceModelb)) {
            return Result.error(400, "将要转移到的客服信息不正确，不存在该客服");
        }
        List<Integer> integerLista = convertStringToIntList(customerServiceModela.getVipIds(), ",");
        if (integerLista.isEmpty()) {
            return Result.error(400, "原客户中已经不存在该商家");
        }
        List<Integer> integerListb = convertStringToIntList(customerServiceModelb.getVipIds(), ",");
        integerLista.remove(businessId);
        integerListb.add(businessId);
        String a = convertIntListToString(integerLista, ",");
        String b = convertIntListToString(integerListb, ",");
        integerListb.add(businessId);
        customerServiceModelb.setVipIds(b);
        customerServiceModela.setVipIds(a);
        customerServiceMapper.updateById(customerServiceModelb);
        customerServiceMapper.updateById(customerServiceModela);
        return Result.success("转移成功");
    }

    /**
     * 客服的分页查询
     *
     * @param pageNo
     * @param pageSize
     * @param areaId
     * @param keyword
     * @return
     */
    @Override
    public Result getlist(Integer pageNo, Integer pageSize, Integer areaId, String keyword) {
        MPJQueryWrapper<CustomerServiceModel> wrapper = new MPJQueryWrapper<>();
        wrapper.selectAll(CustomerServiceModel.class).
                select("ta.area", "tc.city", "tp.province")
                .leftJoin("tbc_areas ta on t.area_id = ta.area_id")
                .leftJoin("tbc_cities tc on ta.city_id = tc.city_id")
                .leftJoin("tbc_provinces tp on tc.province_id = tp.province_id")
                .eq("t.is_del",2)
                .eq(areaId != null, "t.area_id", areaId)
                .eq(StrUtil.isNotBlank(keyword), "t.name", keyword).or().eq(StrUtil.isNotBlank(keyword), "t.phone", keyword).or().eq(StrUtil.isNotBlank(keyword), "t.email", keyword);
        IPage<CustomerServiceModel> page = new Page<>();
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        customerServiceMapper.selectPage(page, wrapper);
        List<CustomerServiceModel> records = page.getRecords();
        for (CustomerServiceModel record : records) {
            record.setAreaText(record.getProvince() + "/" + record.getCity() + "/" + record.getArea());
        }
        IntegralVoucherPageVo vo = new IntegralVoucherPageVo();
        vo.setCount((int) page.getTotal());
        vo.setCustomerServiceModelList(records);
        return Result.success(vo);
    }

    @Override
    public Result selectList() {
        QueryWrapper<CustomerServiceModel> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.eq("status", 2);
        wrapper.eq("is_del", 2);
        return Result.success(customerServiceMapper.selectList(wrapper));
    }


    /**
     * 把List<Integer>类型转换成String形式
     *
     * @param intList
     * @param delimiter
     * @return
     */
    public static String convertIntListToString(List<Integer> intList, String delimiter) {
        StringBuilder sb = new StringBuilder();
        // 遍历整数列表，将整数转换为字符串并添加到StringBuilder中
        for (Integer num : intList) {
            sb.append(num).append(delimiter);
        }
        // 删除最后一个分隔符
        if (sb.length() > 0) {
            sb.setLength(sb.length() - delimiter.length());
        }
        return sb.toString();
    }

    /**
     * 把String类型转换成List<Integer>形式
     *
     * @param str
     * @param delimiter 327.2 81.8
     * @return
     */
    public static List<Integer> convertStringToIntList(String str, String delimiter) {
        if (StrUtil.isBlank(str)) {
            return new ArrayList<>();
        }
        // 使用给定的分隔符分割字符串
        String[] items = str.split(delimiter);

        // 创建一个列表来保存整数
        List<Integer> intList = new ArrayList<>();

        // 将每个字符串转换为整数并添加到列表中
        for (String item : items) {
            intList.add(Integer.parseInt(item.trim())); // trim()用于去除字符串两端的空白字符
        }

        return intList;
    }
}
